package com.wuye.controller;

import com.wuye.model.*;
import com.wuye.service.*;
import com.wuye.web.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.*;

import org.springframework.stereotype.Controller;
import org.apache.commons.logging.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class WuyeAdminController {
    @Autowired
    private SessionHandler ssd;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SessionHandler sessionHandler;
    @Autowired
    private AppConfig config;
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private AppConfig appConfig;

    private Log log = LogFactory.getLog(this.getClass());

    @RequestMapping(value = "/loginAction.jspx")
    @ResponseBody
    public String adminLogon(@RequestParam(value = "password", required = false) String password, HttpSession session) {
        try {
            if (config.getAdminPassword().equals(password)) {
                AdminSession us = sessionHandler.getAdminSession(session);
                JSONObject json = ST.ok.getJsonObject();
                return json.toString();
            }
            JSONObject json = ST.loginWrongPassword.getJsonObject();
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }

    @RequestMapping(value = "/loginOut.jspx")
    public String adminLogon(HttpSession session) {
        sessionHandler.adminSessionExists(session);
        sessionHandler.removeSession(session);
        return "redirect:/admin/login.jspx";
    }

    @RequestMapping(value = "/listDayBook.jspa")
    @ResponseBody
    public String listDayBook() {
        log.info("---listDayBook");
        log.info("---" + config.getImagePath());
        List<Order> orderList = orderService.getDayBook();
        log.info(orderList.get(0).toString());
        JSONObject json = new JSONObject();
        json.put("orderDetails", orderList);
        log.info(json);
        return json.toString();
    }

    @RequestMapping("/saveUser.jspa")
    public String saveUser(User user) {
        String cellPhone = user.getCellPhone();
        User users = userService.checkUser(cellPhone);
        if (users == null) {
            userService.saveUser(user);
            return ST.ok.toJson();
        } else {
            return ST.userExist.toJson();
        }

    }

    @RequestMapping("/updates.jspa")
    public ModelAndView updates(HttpSession session){
        MenuPropers pro = ssd.getAdminSession(session).getMenus();
        String menuId = pro.getMenuId();
        MenuDetail menu = menuService.findOneMenu(menuId);
        for (MenuType menus : MenuType.values()) {
            if (menus.toString().equals(menu.getItemType())) menu.setItemType(menus.getMenuType());
        }
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/admin/jspa/menu/updateMenu");
        mv.addObject("menus",menu);
        return mv;
    }

    @RequestMapping("/updateMenus.jspa")
    public String updateMenu(String menuId,HttpSession session) {
        AdminSession adminSession = ssd.getAdminSession(session);
        MenuPropers pro = adminSession.getMenus();
        pro.setMenuId(menuId);
        return "redirect:/admin/updates.jspa";
    }



    @RequestMapping("/uploadFile.jspa")
    public String uploadImg(@RequestParam(value = "file") MultipartFile file, Menu menu,HttpSession session,String storeNum) {
        if (file.getSize() > 0) {
            String path = appConfig.getImagePath();
            String fileName = String.valueOf(new Date().getTime());
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
                menu.setImageFile(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for(MenuType me:MenuType.values()){
            if(me.getMenuType().equals(menu.getItemType())){
                menu.setItemType(me.toString());
                break;
            }
        }
        menuService.updateMenu(menu,storeNum);
        return "redirect:/admin/queryMenu.jspa";
    }

    //商品上架
    @RequestMapping("/isUpDown2.jspa")
    @ResponseBody
    public String updateOnline2(String menuId) {
        menuService.updateMenuStatus2(menuId);
        return ST.ok.toJson();
    }

    //商品下架
    @RequestMapping("/isUpDown.jspa")
    @ResponseBody
    public String updateOnline(String menuId) {
        menuService.updateMenuStatus(menuId);
        return ST.ok.toJson();
    }
    //删除菜品
    @RequestMapping("/deleteMenu.jspa")
    public String deleteMenu(String menuId) {
        menuService.deleteMenuss(menuId);
        return "redirect:/admin/queryMenu.jspa";
    }

    //修改库存数量
    @RequestMapping("/storeUpdate.jspa")
    @ResponseBody
    public String storeUpdare(String menuId,String nums){
        menuService.storeCount(menuId,nums);
        return ST.ok.toJson();
    }



    //重定向到真正的分页查询
    @RequestMapping("/queryMenu.jspa")
    public ModelAndView queryMenu(HttpSession session){
        AdminSession se = ssd.getAdminSession(session);
        MenuPropers pro = se.getMenus();
        List<Object[]> menu = new ArrayList<Object[]>();
        String itemName = pro.getMenuName();
        String itemType = pro.getMenuType();
        String curpage = pro.getCurpage();
        menu = menuService.queryAllByMenunameDivide(itemName, itemType, curpage);
        List<MenuDetail> menus = null;
        if(menu.size()>0) {
            menus = menuService.convertList(menu);
        }
        ModelAndView md = new ModelAndView();
        md.setViewName("/admin/jspa/menu/menuList");
        md.addObject("menus", menus);
        int curs = 0;
        if (StringUtils.isBlank(pro.getCurpage())) {
            curs = 1;
        } else {
            curs = Integer.parseInt(curpage);
        }
        if (StringUtils.isNotBlank(itemName)) {
            md.addObject("itemName", itemName);
        } else {
            md.addObject("itemName", "");
        }
        if (StringUtils.isBlank(itemType) || itemType.equals("1")) {
            md.addObject("itemType", "1");
        } else {
            md.addObject("itemType", itemType);
        }
        int pa = menuService.sumAllMenu(itemType, itemName);
        md.addObject("pa", pa);
        md.addObject("curs", curs);
        JSONObject json = menuService.orderTimes();
        String str1 = (String)json.get("s1");
        String str2 = (String)json.get("s2");
        md.addObject("str1",str1);
        md.addObject("str2",str2);
        return md;
    }

    //分页查询菜品列表@RequestParam(value="itemName", defaultValue="")    @RequestParam(value="itemType", defaultValue="")
    @RequestMapping("/queryMenus2.jspa")
    public String queryMenus2(@RequestParam(value="itemName", defaultValue="") String itemName,
                              @RequestParam(value="itemType", defaultValue="") String itemType,
                              @RequestParam(value="curpage", defaultValue="") String curpage,HttpSession session) {
        AdminSession adminSession = ssd.getAdminSession(session);
        MenuPropers pro = adminSession.getMenus();
        pro.setMenuName(itemName);
        pro.setCurpage(curpage);
        pro.setMenuType(itemType);
        adminSession.setMenus(pro);
        ssd.saveAdminSession(adminSession,session);
        return "redirect:/admin/queryMenu.jspa";
    }


    //增加菜品
    @RequestMapping("/addMenus")
    public String addMenus(MultipartFile file,Menu menu,String storeNum){
        if (file.getSize() > 0) {
            String path = appConfig.getImagePath();
            String fileName = String.valueOf(new Date().getTime());
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                file.transferTo(targetFile);
                menu.setImageFile(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        menuService.addMenu(menu,storeNum);
        return "redirect:/admin/queryMenus2.jspa";
    }

    //查询订单
    @RequestMapping("/queryOrd")
    public ModelAndView queryOrd(HttpSession session){
        AdminSession sess = ssd.getAdminSession(session);
        MenuPropers pro = sess.getMenus();
        String begin = pro.getBegins();
        String end = pro.getEnds();
        String orderStatus = pro.getStatus();
        try {
            List<OrderDetail> lists = orderService.getAllOrderListss(begin,end,orderStatus);
            ModelAndView mv = new ModelAndView();
            mv.setViewName("/admin/jspa/order/orderList");
            mv.addObject("orders", lists);
            String dd = "";
            if (StringUtils.isBlank(begin) && StringUtils.isBlank(end)) {
                dd = Constant.sdfDay.format(new Date());
                mv.addObject("dates", dd);
            } else if(StringUtils.isBlank(begin)){
                mv.addObject("ends",end);
            }else if(StringUtils.isBlank(end)){
                mv.addObject("begins",begin);
            }else{
                mv.addObject("begins",begin);
                mv.addObject("ends",end);
            }
            mv.addObject("dates", dd);
            String status = "";
            if(StringUtils.isBlank(orderStatus)){
                status = "1";
            }else{
                status = orderStatus;
            }
            mv.addObject("status",status);
            return mv;
        } catch (Exception e) {
            return null;
        }
    }

    //查询订单列表
    @RequestMapping("/queryOrderList.jspa")
        public String queryOrderList(@RequestParam(value="begin", defaultValue="") String begin,
                                       @RequestParam(value="end", defaultValue="") String end,
                                       @RequestParam(value="orderStatus", defaultValue="") String orderStatus,HttpSession session) {
        AdminSession sess = ssd.getAdminSession(session);
        MenuPropers pro = sess.getMenus();
        pro.setBegins(begin);
        pro.setEnds(end);
        pro.setStatus(orderStatus);
        sess.setMenus(pro);
        ssd.saveAdminSession(sess,session);
        return "redirect:/admin/queryOrd";
    }
    @RequestMapping("/updateOrderStatus.jspa")
    //只有生成订单时会产生订单状态，已完成订单状态
    @ResponseBody
    public String updateOrderStatus(String orderNum) {
        orderService.updateOrder(orderNum);
        return ST.ok.toJson();
    }

    //批量处理订单
    @RequestMapping("/statusChange.jspa")
    @ResponseBody
    public String statusChange(String nums) {
        String[] str = nums.split(",");
        for(String ord : str){
            Order order = orderService.queryOrderStatus(ord);
            String type = order.getOrderState();
            if(type.equalsIgnoreCase("CONFIRM")){
                orderService.updateOrder(ord);
            }else{
                return ST.orderStateError.toJson();
            }
        }
        return ST.ok.toJson();
    }


    @RequestMapping("/cancelOrder2.jspa")
    @ResponseBody
    public String cancleOrder(String orderNum) {
        orderService.updateOrderCancel(orderNum);
        return ST.ok.toJson();
    }
    //退款处理
    @RequestMapping("/refund.jspa")
    @ResponseBody
    public String refund(String orderNum){
        orderService.refundOrder(orderNum);
        return ST.ok.toJson();
    }
    //财务查询订单
    @RequestMapping("/queryFinance.jspa")
    public ModelAndView queryFinance(String dateTime,String endTime) {
        try {
//            List<OrderDetail> lists = orderService.getAllOrderListss(dateTime,endTime);
            ModelAndView mv = new ModelAndView();
            mv.setViewName("/admin/jspa/finance/financeDetail");
//            mv.addObject("orders", lists);
            String dd = null;
            if (dateTime == null || dateTime.equals("")) {
                dd = Constant.sdfDay.format(new Date());
            } else {
                dd = dateTime;
            }
            mv.addObject("dates", dd);
            return mv;
        } catch (Exception e) {
            return null;
        }
    }


    //修改订餐时间
    @RequestMapping("/updateArriveTimes.jspa")
    @ResponseBody
    public String updateArriveTimes(String beginTime,String endTime,HttpSession session){
        String[] str = beginTime.split(":");
        if(Integer.valueOf(str[0])<10) str[0] = "0"+str[0];
        beginTime = str[0]+":"+str[1]+":"+str[2];

        String[] str2 = endTime.split(":");
        if(Integer.valueOf(str2[0])<10) str2[0] = "0"+str2[0];
        endTime = str2[0]+":"+str2[1]+":"+str2[2];
        String path = appConfig.getImagePath();
        File file = new File(path,"sendTime.txt");
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byte[] bytes = (beginTime+endTime).getBytes();
        FileOutputStream outs = null;
        try {
            if(!file.exists()) file.createNewFile();
            outs  = new FileOutputStream(file);
            outs.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(outs !=null) {
                try {
                    outs.flush();
                    outs.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        return ST.ok.toJson();
    }
    //主页时间修改
    @RequestMapping("/pageUpdate.jspa")
    @ResponseBody
    public String pageUpdate(String times){
        AppConfig.pageTime = times;
        return ST.ok.toJson();
    }
    //订餐时间回显
    @RequestMapping("/showresTime.jspa")
    public ModelAndView showresTime(){
        ModelAndView md = new ModelAndView();
        JSONObject json = menuService.orderTimes();
        String str1 = (String)json.get("s1");
        String str2 = (String)json.get("s2");
        md.addObject("str1",str1);
        md.addObject("str2",str2);
        md.setViewName("/admin/jspa/restaurant/restTime");
        return md;
    }
}